<?php
namespace App\Admin\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class User extends Authenticatable
{
    use HasFactory;
    use TwoFactorAuthenticatable;

    protected $table = 'system_user';

    // 可以批量赋值属性
    protected $fillable = [
        'email', 
        'mobile', 
        'name', 
        // 'nickname', 
        // 'username', 
        'password', 
        'status', 
        'profile_photo_path',
    ];

    protected $casts = [
        'password' => 'hashed',
    ];
    
    // 隐藏属性
    protected $hidden = [
        'password',
        // 'profile_photo_path',
        'two_factor_secret',
        'two_factor_recovery_codes',
        'two_factor_confirmed_at',
    ];

    protected $appends = ['profile_photo_url'];


    /**
     * 要附加到模型数组表单的访问器。
     *
     * @var array
     */
    // protected $appends = ['role_id'];

    /**
     * 为 array / JSON 序列化准备日期格式。
     */
    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'system_user_role', 'user_id', 'role_id')->select(['role_id']);
    }

    public function getRoleIdsAttribute()
    {
        return $this->roles->pluck('role_id');
    }
    public function profilePhotoUrl(): Attribute
    {
        return Attribute::get(function (): string {
            return $this->profile_photo_path
                    ? Storage::disk('public')->url($this->profile_photo_path)
                    : url('/images/noavatar_big.gif') ;
        });
    }
}